<template>
  <div class="ccui-app-container">
    <div class="ccui-advanced-search-wrapper ccui-clearfix">
      <el-search
        ref="search"
        :formProp="formData"
        @search="search"
        :isShowSearch="isShowSearch"
        class="ccui-highsearch"
        :selectClear="true"
        :spoNum="2"
        @change="change"
      >
        <div class="ccui-tab-wrapper">
          <el-button
            :type="isActive === index ? 'table-top-active' : 'table-top'"
            size="mini"
            v-for="(item, index) in focuses"
            :key="'tab' + index"
            @click="tabChange(item.focus)"
          >
            <template v-if="item.focus === 'whole'">全部</template>
            <template v-if="item.focus === 'un-submitted'">待提交</template>
            <template v-else-if="item.focus === 'under-approval'"
              >审批中</template
            >
            <template v-else-if="item.focus === 'return-approval'"
              >审批退回 ({{ totalNum }})</template
            >
          </el-button>
          <!-- <template v-else-if="item.focus === 'no-approval'"
              >审批不通过</template
            > -->
        </div>
        <!--  v-if="form.contractStatus == 4" -->
        <div class="ccui-extend-btn">
          <el-button
            size="mini"
            type="primary-icon-big"
            @click="handleGoNew"
            icon="icon-ccui-add-sup"
            >新增</el-button
          >
        </div>
        <template slot="search">
          <el-input
            v-model="formData.storageName"
            clearable
            searchLabel="入库单名称"
            placeholder="请输入入库单名称模糊查询"
            @blur="handleTrim('storageName')"
          ></el-input>
          <el-input
            v-model="formData.storageCode"
            clearable
            searchLabel="入库单编号"
            placeholder="请输入入库单编号模糊查询"
          ></el-input>
          <el-input
            v-model="formData.supplierName"
            clearable
            searchLabel="供应商"
            placeholder="请输入供应商模糊查询"
          ></el-input>
          <el-input
            v-model="formData.reportInOrgName"
            clearable
            searchLabel="填报单位"
            placeholder="请输入填报单位模糊查询"
          ></el-input>
          <el-input
            v-model="formData.warehouseName"
            clearable
            searchLabel="仓库"
            placeholder="请输入仓库模糊模糊查询"
          ></el-input>
          <el-input
            v-model="formData.thirdCategoriesOfName"
            clearable
            searchLabel="分类名称"
            placeholder="请输入分类名称模糊查询"
          ></el-input>
        </template>
        <!-- 表单高级搜索 -->
        <el-input
          v-model="formData.storageName"
          clearable
          searchLabel="入库单名称"
          placeholder="请输入入库单名称模糊查询"
          slot="searchItem3"
          @blur="handleTrim('storageName')"
        ></el-input>
        <el-input
          v-model="formData.storageCode"
          clearable
          searchLabel="入库单编号"
          placeholder="请输入入库单编号模糊查询"
          slot="searchItem2"
        ></el-input>
        <el-input
          v-model="formData.supplierName"
          clearable
          searchLabel="供应商"
          placeholder="请输入供应商模糊查询"
          slot="searchItem4"
        ></el-input>
        <el-input
          v-model="formData.reportInOrgName"
          clearable
          searchLabel="填报单位"
          placeholder="请输入填报单位模糊查询"
          slot="searchItem5"
        ></el-input>
        <el-input
          v-model="formData.warehouseName"
          clearable
          searchLabel="仓库"
          placeholder="请输入仓库模糊查询"
          slot="searchItem6"
        ></el-input>
        <el-input
          v-model="formData.thirdCategoriesOfName"
          clearable
          searchLabel="分类名称"
          placeholder="请输入分类名称模糊查询"
          slot="searchItem7"
        ></el-input>
      </el-search>
    </div>
    <!-- 表格 -->
    <div class="ccui-multifunctional-table-wrapper">
      <el-table
        ref="multipleTable"
        :data="tableData"
        :fit="true"
        :row-style="rowClass"
        :cell-style="cellStyle"
        border
        class="ccui-multifunctional-table"
        @header-dragend="tableTitleWidth"
        @sort-change="sortChange"
        max-height="9999"
        v-if="draggFlag"
      >
        <el-table-column label="序号" width="60" fixed>
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column label="入库单编号" width="200" fixed>
          <template slot-scope="scope">
            <span
              :style="{ color: 'rgb(0, 137, 239)', cursor: 'pointer' }"
              @click="handleGoDetail(scope.row)"
              >{{ scope.row.storageCode }}</span
            >
          </template>
        </el-table-column>

        <template v-for="(table, index) in unfixedTableThead">
          <el-table-column
            :fixed="table.fixed || false"
            :key="'one' + index"
            :type="table.type"
            :label="table.label"
            :align="table.align || 'left'"
            :header-align="table.headerAlign || 'left'"
            :min-width="table.width"
            :prop="table.prop"
            :show-overflow-tooltip="true"
            border="true"
          >
          </el-table-column>
        </template>
        <el-table-column label="操作" width="50" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-if="true"
              size="mini"
              type="text"
              @click="handleGoEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <!-- <el-button
              v-if="true"
              size="mini"
              type="text"
              @click="handleGoDetail(scope.$index, scope.row)"
              >查看</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
      <div class="ccui-table-footer" v-show="isShowPagination">
        <div id="ccui-paging">
          <el-pagination
            :total="totalNum"
            :page-size="pageSizeCode"
            :current-page="pageNoCode"
            :page-sizes="[10, 20, 50, 100, 200, 500]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            popper-class="ccui-paging-page-size-popper"
            @prev-click="handlePrev"
            @next-click="handleNext"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <el-button
            class="ccui-pagination-btn"
            size="mini"
            type="default"
            @click="handleSizeChange('none')"
            >确定</el-button
          >
        </div>
      </div>
    </div>
    <!-- 表格end -->
  </div>
</template>

<script>
import { listFinStoragePage } from "../../api/item-list";
import getPower from "@/basa/utils/getPower.js";
import { setSessionItem, getSessionItem } from "@/basa/utils";
import peopleManageMixin from "../../mixins/peopleManage.js";
import approvalState from "@/config/mixins/smp-state";

export default {
  mixins: [getPower, peopleManageMixin, approvalState],
  data() {
    return {
      isActive: 3,
      isShowDetail: true,
      isShowEdit: true,
      multiDataToEnd: {},
      singleDataToEnd: {},
      // 表格相关
      tableData: [], // 表格数据
      draggFlag: true,
      tableName: this.tableList.mcconcmeasurebasicList, // 表格命名
      tableThead: [], // 表格数据
      // 锁定表格
      fixedTableThead: [
        {
          label: "序号",
          prop: "id",
          width: "38",
          checked: true,
          fixed: true,
          type: "index",
          resizable: false
        },
        {
          label: "入库单编号",
          prop: "storageCode",
          width: "200",
          fixed: true
        }
      ],
      // 非锁定表格
      unfixedTableThead: [
        {
          label: "入库单名称",
          prop: "storageName",
          width: "300"
        },
        {
          label: "供应商",
          prop: "supplierName",
          width: "200"
        },
        {
          label: "仓库",
          prop: "warehouseName",
          width: "180"
        },
        {
          label: "填报单位",
          prop: "reportInOrgName",
          width: "200"
        },
        {
          label: "入库类型",
          prop: "storageType",
          width: "90"
        },
        {
          label: "入库数量",
          prop: "storageCount",
          width: "140"
        },
        {
          label: "含税金额",
          prop: "storageMoney",
          width: "140",
          align: "right"
        },
        // {
        //   label: "不含税金额",
        //   prop: "afterDutyMoney",
        //   width: "62"
        // },
        {
          label: "分类名称",
          prop: "thirdCategoriesOfName",
          width: "130"
        },
        {
          label: "状态",
          prop: "storageStatus",
          width: "70"
        }
      ],
      // 动态表格
      tableTheadOptions: [],
      // 弹框表格
      // popoverShow: false,
      selectRow: [],
      selectData: [],
      isFocus: 1,
      // 表格相关 end
      // 高级搜索数据 start
      formData: {
        storageCode: "", // 入库单编号
        storageName: "", // 入库单名称
        thirdCategoriesOfName: "", // 分类名称
        supplierName: "", // 供应商名称
        reportInOrgName: "", // 填报单位名称
        warehouseName: "" // 仓库名称
      }, // 高级搜索提交数据
      formDataSearch: "",
      localSearchData: {},
      isShowSearch: true,
      isShow: false,
      // 高级搜索数据 end
      isShowPagination: false, //无数据的不展示底部全选，批量删除
      // 全选以及页码
      totalNum: 0,
      total: 0,
      isIndeterminate: false,
      checkAll: false,
      value: "",
      pageNoCode: 1, // this.getLocalPageNo()
      pageSizeCode: 10, //this.getLocalPageSize()
      // isFist: false,
      // 全选以及页码 end
      // 表格数据删除相关
      delDemoId: "",
      content: "您确定要删除吗？",
      typeDel: "", //有关批量删除
      isSelection: false,
      // 表格数据删除相关 end
      // 排序入参所需字段
      sortord: "",
      sortprop: "",
      // 表格数据相关处理 end
      form: {}
    };
  },
  computed: {},
  watch: {},
  created() {},
  methods: {
    change(index, key, value) {
      const formDataKeys = Object.keys(this.formData);
      formDataKeys.map(_ => {
        if (_ !== key) this.formData[_] = "";
      });
    },
    // 跳转编辑页
    handleGoEdit(index, row) {
      if (
        window.location.pathname ==
        "/inventoryManagement/financialList/return-approval"
      ) {
        this.$router.push(
          `/inventoryManagement/financialList/edit-item/${row.id}`
        );
      } else {
        this.$router.push(
          `/inventoryManagement/financeWarehousing/edit-item/${row.id}`
        );
      }
    },
    // 查看
    handleGoDetail(row) {
      if (
        window.location.pathname ==
        "/inventoryManagement/financialList/return-approval"
      ) {
        this.$router.push(
          `/inventoryManagement/financialList/item-detail-approval/${row.id}`
        );
      } else {
        this.$router.push(
          `/inventoryManagement/financeWarehousing/item-detail-approval/${row.id}`
        );
      }
    },
    //跳转新增页
    handleGoNew() {
      if (
        window.location.pathname ==
        "/inventoryManagement/financialList/return-approval"
      ) {
        this.$router.push("/inventoryManagement/financialList/add-item");
        sessionStorage.setItem("storageType", 2);
      } else {
        this.$router.push("/inventoryManagement/financeWarehousing/add-item");
        sessionStorage.setItem("storageType", 1);
      }
    },
    initData() {
      this.isShow = false;
      // this.getList();
      this.setTableWidth();
      this.renderTable();
      // this.isFist = false;
    },
    // 根据返回状态显示不同的文字颜色
    // eslint-disable-next-line no-unused-vars
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "transparent" };
      }
    },
    // 默认渲染表格
    renderTable() {
      const localTableData = localStorage.getItem(this.tableName)
        ? JSON.parse(localStorage.getItem(this.tableName))
        : [];
      let unfixedTableThead = this.unfixedTableThead.concat(
        this.fixedTableThead
      );
      let localTableDataStr = localTableData.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );
      let unfixedTableTheadStr = unfixedTableThead.map(
        ({ label, prop, width, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );

      if (localTableData.length === unfixedTableThead.length) {
        let flag = localTableDataStr.every(item =>
          unfixedTableTheadStr.includes(item)
        );
        if (flag) {
          // 完全相同
          this.tableTheadOptions = localTableData;
          this.tableThead = localTableData;
          this.unfixedTableThead = localTableData.filter(item => {
            return !this.fixedTableThead.find(
              cItem => item.prop === cItem.prop
            );
          });
        } else {
          // 长度相同但值不同
          this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
          const comment = JSON.stringify(this.tableThead);
          localStorage.setItem(this.tableName, comment);
          const localTableData = JSON.parse(
            localStorage.getItem(this.tableName)
          );
          this.tableTheadOptions = localTableData;
        }
      } else {
        // 长度不同
        this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
        const comment = JSON.stringify(this.tableThead);
        localStorage.setItem(this.tableName, comment);
        const localTableData = JSON.parse(localStorage.getItem(this.tableName));
        this.tableTheadOptions = localTableData;
      }
    },
    // 表格弹框拖拽触发
    handleTableChange(val) {
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      this.tableTheadOptions = localTableData;
    },
    // 是否显示对应列
    handleUpdate(item, index) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (i === index) {
          this.unfixedTableThead.checked = !this.unfixedTableThead.checked;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      this.tableTheadOptions = localTableData;
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (this.unfixedTableThead[i].label === column.label) {
          this.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.draggFlag = false;
      this.$nextTick(() => {
        this.draggFlag = true;
      });
    },
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "rgba(255,232,195,1) " };
      }
    },
    // 批量删除并刷新列表
    handleDelSelected() {
      if (this.idArrSelected) {
        this.typeDel = "all";
        this.deleteLog();
      } else {
        this.$message({
          message: "请选择您要删除的数据",
          type: "warning"
        });
      }
    },
    // 上一页
    handlePrev() {
      console.log("上一页");
    },
    // 下一页
    handleNext() {
      console.log("下一页");
    },
    // 每页条数发生改变
    handleSizeChange(val) {
      this.pageNoCode = 1;
      if (val !== "none") {
        this.pageSizeCode = val;
        setSessionItem("pageSize", this.tableName, val);
      }
      this.getList(this.formDataSearch);
    },
    // 当前页发生改变
    handleCurrentChange(val) {
      let searchFormData = getSessionItem("pageNo", this.tableName) || {};
      setSessionItem("pageNo", this.tableName, {
        pageNo: val,
        searchForm: searchFormData.searchForm || {}
      });
      this.formDataSearch = {
        ...this.formDataSearch,
        ...searchFormData.searchForm
      };
      // 跳转翻页都会调这个方法
      this.pageNoCode = val;
      this.getList(this.formDataSearch);
    },
    // 高级搜索所需函数 start
    // 高级搜索展开按钮
    search(searchData) {
      this.pageNoCode = 1;
      this.formDataSearch = JSON.parse(JSON.stringify(searchData));
      this.localSearchData = JSON.parse(JSON.stringify(searchData));
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
      this.getList(this.formDataSearch);
    },
    // 高级搜索 end
    // 金额四舍五入
    calculateFilter(data) {
      if (data || data == 0) {
        if ((data + "").indexOf(".") != -1) {
          let newData = (data + "").substring(0, (data + "").indexOf(".") + 3);
          return newData;
        } else {
          return data;
        }
      } else {
        return "";
      }
    },
    // 数量四舍五入
    numberFilter(data) {
      if (data || data == 0) {
        if ((data + "").indexOf(".") != -1) {
          console.log("走这步了");
          let newData = (data + "").substring(0, (data + "").indexOf(".") + 4);
          return Number(newData).toFixed();
        } else {
          return data;
        }
      } else {
        return "";
      }
    },
    // 列表数据请求
    getList(reqObj) {
      console.log(this.pageNoCode);
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.pageNo = this.pageNoCode;
      obj.storageStatus = 6;
      if (
        window.location.pathname ==
        "/inventoryManagement/financialList/return-approval"
      ) {
        obj.storageType = 2; // 财务暂存入库
      } else {
        obj.storageType = 1; // 财务入库
      }
      obj.pageSize = this.pageSizeCode;
      obj.isShowPageLoading = true;
      // obj.reportInOrgId = JSON.parse(window.sessionStorage.userDetal).orgId;
      listFinStoragePage(obj)
        .then(res => {
          console.log(res);
          if (res.data.data.rows.length == 0 && this.pageNoCode > 1) {
            this.pageNoCode--; //自减一页
            //重新自调用接口
            this.getList();
            return;
          }
          this.isShowPagination = res.data.data.recordsTotal > 0;
          this.tableData = res.data.data.rows;
          this.totalNum = res.data.data.recordsTotal;
          this.total = res.data.data.total;
          this.pageNoCode = res.data.data.pageNo; // 当前页
          this.tableData.forEach(item => {
            item.storageCount = (+item.storageCount).toFixed(3);
            item.storageMoney = (+item.storageMoney).toFixed(2);
            if (item.storageType == 1) {
              item.storageType = "正式入库";
            } else if (item.storageType == 2) {
              item.storageType = "暂估入库";
            }
            item.statusCode = item.storageStatus;
            item.storageStatus =
              this.smpScStatusTypeName[Number(item.storageStatus)];
          });
        })
        .catch(e => {
          // console.log(e);
        });
    },

    toggleSelection(rows) {
      this.$refs.multipleTable.clearSelection();
      const arr = [];
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
          arr.push(row.id);
        });
        this.idArrSelected = arr;
      }
    },
    // 排序
    sortChange(params) {
      this.sortord = params.order;
      this.sortprop = params.prop;
      this.getList();
    },
    // 默认显示多少条
    getLocalPageSize() {
      return (
        getSessionItem("pageSize", this.tableList.mcconcmeasurebasicList) || 10
      );
    },
    // 读取当前页缓存
    getLocalPageNo() {
      let localData = getSessionItem(
        "pageNo",
        this.tableList.mcconcmeasurebasicList
      );
      return (localData && localData.pageNo) || 1;
    },
    // input 输入框去掉前后空格
    handleTrim(key) {
      this.$set(
        this.formData,
        key,
        this.formData[key].replace(/(^\s*)|(\s*)$/g, "")
      );
    }
  },
  mounted() {
    this.initData();
  },
  // beforeRouteLeave(to, from, next) {
  //   for (var key in this.$vnode.parent.parent.componentInstance.cache) {
  //     delete this.$vnode.parent.parent.componentInstance.cache[
  //       ishasAgentId(to.path, key)
  //     ];
  //   }
  //   next();
  // },
  activated() {
    this.$refs.search.resetForm();
    this.search(this.formData);
    if (Object.keys(this.localSearchData).length > 0) {
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
    }
    let localData = getSessionItem(
      "pageNo",
      this.tableList.mcconcmeasurebasicList
    );
    let data = localData && localData.searchForm;
    this.getList({ ...this.formDataSearch, ...data });
  }
};
</script>
<style lang="scss" scoped>
/deep/.ccui-multifunctional-table {
  .el-table__fixed-right,
  .el-table__fixed {
    height: 100% !important;
  }
}
/deep/.el-search .el-searchs-bottom .el-form .el-row .el-col-12 {
  width: 33.33333%;
}
// 解决表格定位滚动条无法拖动
/deep/ .el-table__fixed-header-wrapper {
  th {
    pointer-events: auto;
  }
}
/deep/ .el-table__fixed,
/deep/.el-table__fixed-right {
  pointer-events: none;
  td {
    pointer-events: auto;
  }
}
</style>
